package com.yfl.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.yfl.common.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户的控制器
 */
@RestController
@RequestMapping("/sysuser")
public class SysUserController {
    /**
     * 用户登陆
     * @param username 用户名
     * @param password 用户密码
     */
    @PostMapping("/login.do")
    public Result doLogin(String username, String password,String code){

        // 校验验证码
        validateCode(code);
        // 创建token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 获取主体
        Subject subject = SecurityUtils.getSubject();
        // 执行登陆-->userRealm.doGetAuthorizationInfo
        subject.login(token);
        // 没有异常就登陆成功
        System.out.println("登陆成功");
        return Result.ok();
    }

    /**
     * 用户的登出
     * @return
     */
    @GetMapping("/logout.do")
    public Result logout(){
        // shiro 实现登出
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok();
    }


    @GetMapping("/codeImg.do")
    public void createCodeImg(HttpServletResponse response, HttpSession session) throws IOException {
        // 创建验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(130, 48, 1, 0);
        // 保存验证码
        session.setAttribute("CODE_IMG", circleCaptcha.getCode());
        // 将验证码写出去
        circleCaptcha.write(response.getOutputStream());

    }

    /**
     * 校验验证码
     * @param code
     */
    private void validateCode(String code) {
        // 1 获取session 里面的验证码
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        Object codeImg = session.getAttribute("CODE_IMG");
        if (codeImg == null) {
            throw new IllegalArgumentException("请获取验证码后重试!");
        }
        // 2 对比2 个验证码
        if (!codeImg.toString().equalsIgnoreCase(code)) {
            throw new IllegalArgumentException("验证码输入错误");
        }

    }

}
